package tools

import (
	"io"
	"time"

	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	"github.com/uber/jaeger-client-go/config"
)

/**
 * 创建追踪者
 *
 * @params string serviceName
 * @params string jaegerAgentURL
 * @author huwl
 * @date 2025/08/09 16:35:48
 */
func NewTracer(serviceName, jaegerAgentURL string) (opentracing.Tracer, io.Closer, error) {
	cfg := &config.Configuration{
		ServiceName: serviceName,
		Sampler: &config.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1, // 全量采样
		},
		Reporter: &config.ReporterConfig{
			LogSpans:            true,
			BufferFlushInterval: 1 * time.Second,
			// LocalAgentHostPort:  jaegerAgentURL, // Jaeger Agent 地址: localhost:6831
		},
	}

	sender, err := jaeger.NewUDPTransport(jaegerAgentURL, 0)
	if err != nil {
		return nil, nil, err
	}

	reporter := jaeger.NewRemoteReporter(sender)

	tracer, closer, err := cfg.NewTracer(
		config.Reporter(reporter),
	)

	return tracer, closer, err
}
